package com.houdoudou.supplier.fragment;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.houdoudou.supplier.R;

import com.houdoudou.supplier.SupplierMainActivity;
import com.houdoudou.supplier.bean.Machine;
import com.houdoudou.supplier.bean.Order;
import com.houdoudou.supplier.bean.OrderProduct;
import com.houdoudou.supplier.bean.Refund;
import com.houdoudou.supplier.common.CommonFunction;
import com.houdoudou.supplier.common.Constant;
import com.houdoudou.supplier.common.DateTimeFunction;
import com.houdoudou.supplier.common.MyAlert;
import com.houdoudou.supplier.common.UniversalHttpPost;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class RefundTodoFrg extends Fragment{

	
	
	ProgressBar prgs;
	TextView resultHint;
	Button refresh,btn_agree,btn_refuse;
	ListView listView;
	View.OnClickListener myOnclickListener;
	CheckBox chooseAll;
	OrderListAdapter listAdapter;
	
	JSONArray ordersJA= new JSONArray();
	boolean isOrderListVailble=false;
	String ISSELECTED="ISSELECTED";
	String AFFAIR_AGREEREFUND="agreeRefund";
	String AFFAIR_REFUSEREFUND="refuseRefund";
	String AFFAIR_SEARCHREFUND="searchRefund";
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view= inflater.inflate(R.layout.frg_refundtodeal, container, false);
		init_listener();
		init_component(view);
		pull_order();
		return view;
	}

	private void init_listener(){
		myOnclickListener= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
			if(v==refresh){
				pull_order();
			}	
			if(v==btn_agree){ //同意退款
	            doSomething(AFFAIR_AGREEREFUND);	  
			}
			if(v==btn_refuse){ //拒绝退款
				 doSomething(AFFAIR_REFUSEREFUND);
				}
			} //onclick
			
		};
	}
	
	private void  doSomething( String affair){
		   JSONArray ja= new JSONArray();
		   for(int i=0;i<ordersJA.size();i++){
			  if(	ordersJA.getJSONObject(i).getBoolean(ISSELECTED)){
				  JSONObject jo= new JSONObject(); 
				  jo.put(Order.ID, ordersJA.getJSONObject(i).getLong(Order.ID));
				  ja.add(jo);
			  }		
			}
		   if(ja.size()==0){
				 MyAlert.simpleDialog(getActivity(), "温馨提示", "请选选择订单，再点操作");
				 return; }
		 	prgs.setVisibility(View.VISIBLE);
			 String[] params= new String[3];
		     params[0]=Constant.BaseUrl+Constant.SupplierUrl;
		     params[1]=affair; //PostCode  
		     JSONObject jsonData= new JSONObject();
		     jsonData.put("supplier", Constant.supplierJO);
		     jsonData.put("orders", ja);
		     params[2]=jsonData.toString();
		     new HttpPostTaskforRefund().execute(params);
	   }
	
	private void pull_order(){
		
		prgs.setVisibility(View.VISIBLE);
		  String[] params= new String[3];
	     params[0]=Constant.BaseUrl+Constant.SupplierUrl;
	     params[1]=AFFAIR_SEARCHREFUND; //PostCode  
	     JSONObject jsonData= new JSONObject();
	     jsonData.put("supplier", Constant.supplierJO);
	     JSONObject refundJOTemp= new JSONObject();
	     refundJOTemp.put(Refund.STATE, 1); //待处理
	     jsonData.put("refund", refundJOTemp);
	     params[2]=jsonData.toString();
	     new HttpPostTaskforRefund().execute(params);
	}
	
	private void init_component(View view){
		prgs= (ProgressBar) view.findViewById(R.id.prgs_frg_frgrefundtodo);
	    resultHint=(TextView) view.findViewById(R.id.tv_functionresult_frg_frgrefundtodo);
		refresh=(Button) view.findViewById(R.id.btn_refresh_frg_frgrefundtodo);
		btn_agree=(Button) view.findViewById(R.id.btn_function1_frg_frgrefundtodo);
		btn_refuse=(Button) view.findViewById(R.id.btn_function2_frg_frgrefundtodo);
		listView= (ListView) view.findViewById(R.id.listview_order_frgrefundtodo);
		chooseAll= (CheckBox) view.findViewById(R.id.ck_chooseall_frgrefundtodo);
		
		prgs.setVisibility(View.GONE);
		
		listAdapter= new OrderListAdapter(getActivity());
		listView.setAdapter(listAdapter);
		
		btn_agree.setOnClickListener(myOnclickListener);
		btn_refuse.setOnClickListener(myOnclickListener);
	    refresh.setOnClickListener(myOnclickListener);
	    
	    chooseAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {	
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				for(int i=0;i<ordersJA.size();i++){
					ordersJA.getJSONObject(i).put(ISSELECTED, isChecked);
					listAdapter.notifyDataSetChanged();
				}		
			}
	    });
	}
class OrderListAdapter extends BaseAdapter {
		   
		
	    private LayoutInflater layoutInflater;  
	    private Context context;  
	    
	   public OrderListAdapter(Context context) {
			super();
			
			this.context = context;
		    this.layoutInflater=LayoutInflater.from(context); 
		}


	  final class Zujian{  
	    public TextView orderId,refundState,refundType,reason,time,money;  
	    public  Button  see;
	    public CheckBox choose;
	   
	  }   //end of Zujian

	      @Override 
	    public int getCount() {
		return ordersJA.size();	  
	}

	   @Override
	  public Object getItem(int position) {
		// TODO Auto-generated method stub
		 return ordersJA.getJSONObject(position);  
	}

	  @Override
	  public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position; 
	}

	  @Override
	  public View getView(int position, View  convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final int selectID = position;   
		 Zujian zj=null;  
	        if(convertView==null){  
	            zj=new Zujian();  
	            //获得组件，实例化组件  
	            convertView=layoutInflater.inflate(R.layout.list_frgrefundtodo, null);    
	            zj.orderId=(TextView) convertView.findViewById(R.id.tv_id_listorder_frgrefundtodo);
	            zj.refundState=(TextView) convertView.findViewById(R.id.tv_state_listorder_frgrefundtodo);
	            zj.money=(TextView) convertView.findViewById(R.id.tv_money_listorder_frgrefundtodo);
	            zj.refundType=(TextView) convertView.findViewById(R.id.tv_type_listorder_frgrefundtodo);
	            zj.reason=(TextView) convertView.findViewById(R.id.tv_reason_listorder_frgrefundtodo);
	            zj.time=(TextView) convertView.findViewById(R.id.tv_time_listorder_frgrefundtodo);
	            zj.see= (Button) convertView.findViewById(R.id.btn_see_listorder_frgrefundtodo);
	            zj.choose= (CheckBox) convertView.findViewById(R.id.ck_choose_listorder_frgrefundtodo);
	            convertView.setTag(zj);  
	            System.out.println("position----"+selectID+"------inflated");
	        }else{   System.out.println("position----"+selectID+"-------not inflated");
	            zj=(Zujian)convertView.getTag();  
	        }  			  
	        //绑定数据  
	        JSONObject record=ordersJA.getJSONObject(selectID).getJSONObject("refund");
	       
	        zj.orderId.setText(""+record.getLong(Refund.ORDERID));
	        zj.refundState.setText(CommonFunction.spellRefundStateWord(record.getInt(Refund.STATE)));
	        zj.reason.setText(record.getString(Refund.REASON));
	        zj.refundType.setText(CommonFunction.spellRefundTypeWord(record.getInt(Refund.TYPE)));
	        zj.money.setText(""+record.getDouble(Refund.MONEY));
	        
	        String dateTimeSL=record.getString(Refund.DATETIMESL);        
	        try {String wordDateTimeAA=DateTimeFunction.transWordDateFormat(dateTimeSL);
	        	zj.time.setText(wordDateTimeAA);
			} catch (Exception e) {e.printStackTrace();	}
	      
	      
	     
	       zj.choose.setChecked(ordersJA.getJSONObject(selectID).getBoolean(ISSELECTED));
	       zj.choose.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			        CheckBox choose=(CheckBox) v;
			        ordersJA.getJSONObject(selectID).put(ISSELECTED, choose.isChecked());  
			}
		   });
	       
	       zj.see.setOnClickListener(new View.OnClickListener() {			
				@Override
				public void onClick(View v) {
					Message msg = new Message();               
                   msg.what=2;
                  msg.arg1=1; //订单管理
                  msg.arg2=5;  //订单详情
                 Bundle bundle= new Bundle(); 
                 bundle.putString("order", ordersJA.getJSONObject(selectID).toString());
                 bundle.putString("tag","order_id_="+ordersJA.getJSONObject(selectID).getLong(Order.ID));
                 bundle.putString("title","订单"+ordersJA.getJSONObject(selectID).getLong(Order.ID));
                 msg.obj=bundle;
                 SupplierMainActivity.myMainHandler.sendMessage(msg);					
				}
			}); 
	       
	        return convertView;
	       } 
	  }// end Adapter
private  class HttpPostTaskforRefund extends android.os.AsyncTask<String,String,Map<String,Object>>{
	@Override
	protected Map<String,Object> doInBackground(String... params) {
		// TODO Auto-generated method stub
		 Map<String,Object> map = new HashMap<String ,Object>();		
	  map =	UniversalHttpPost.doPost(params);	             
		return map;
	}
	
	@Override
	protected void onPostExecute(Map<String,Object> map) {
	
		 System.out.println("-----------onPostExecute()--------------");
		 prgs.setVisibility(View.GONE);
		 String PostResult=(String) map.get("PostResult");		 
		 boolean networkstate=(Boolean) map.get("PostState");
		 if(!networkstate){
			 CommonFunction.alert(getActivity(), "失败", "无网络连接");return;
	      
		}
		//	Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
		    JSONObject json = null;
		    int resultCode=-1;
			String resultInfo="";
			String affair="";				
			JSONObject jo;
			try{
		     json= JSONObject.fromObject(PostResult);
		     resultCode=json.getInt("resultCode");
		     resultInfo=json.getString("resultInfo");	
		     affair =json.getString("affair");	
		     jo= json.getJSONObject("jo");
			}catch(JSONException e){
				 CommonFunction.alert(getActivity(), "失败", "数据解析错误");return;
			}	
	      
			 if(resultCode==1){ CommonFunction.alert(getActivity(), "失败", resultInfo);return; }
			 
	     if(affair.equals(AFFAIR_SEARCHREFUND)){
	    	 ordersJA=jo.getJSONArray("orders");
	    	 
	    	 for(int j=0;j<ordersJA.size();j++){
	    		   ordersJA.getJSONObject(j).put(ISSELECTED, false);}   
	    	 
	    	 if( ordersJA.size()==0) {resultHint.setText("搜索成功，但是并无满足条件的订单"); 
	    	 }else{ resultHint.setText("搜索成功"); }   
	    //	 System.out.println(ordersJA.toString());
	    	 listAdapter.notifyDataSetChanged();
	                   }
	     
	     if(affair.equals(AFFAIR_REFUSEREFUND)||affair.equals(AFFAIR_AGREEREFUND)){
	    	 resultHint.setText(resultInfo);
	    	 JSONArray ordersONline=jo.getJSONArray("orders");
	    	 for(int i=0;i<ordersONline.size();i++){
	    	  long id=ordersONline.getJSONObject(i).getLong(Order.ID);
	    	   for(int j=ordersJA.size()-1;j>=0;j--){
	    		   if(id==ordersJA.getJSONObject(j).getLong(Order.ID)){
	    			   ordersJA.remove(j);
	    		   break; }}
	    	 }
	    	 listAdapter.notifyDataSetChanged();
	        }
	     
					
	} //onPostExecute
} //AsyncTask
}
